import NProgress from 'nprogress'
import useApp, { getInfo } from '@/store/app'
import useChannel from '@/store/channel'
import { getChannelMsgCount, getChatChannelList } from '@/assets/api/dialog-group'
import useUser from '@/store/user'
import { createRouter, createWebHistory } from 'vue-router'

NProgress.configure({ showSpinner: false })

const commonRoutes = [
  {
    path: 'fileManagement',
    name: 'FileManagement',
    component: () => import('@/views/file-management/FileManagement.vue'),
  },
  {
    path: 'personal',
    name: 'Personal',
    component: () => import('@/views/public-view/Personal.vue'),
  },
]

const chatRoute = {
  path: '/chat/:pathMatch(.*)?',
  name: 'Dialog',
  component: () => import('@/views/chat/Chat.vue'),
  children: [],
}

const layoutRoute = {
  path: '',
  name: 'Layout',
  component: () => import('@/layout/Layout.vue'),
  children: [
    chatRoute,
    {
      path: '/redirect',
      name: 'Redirect',
      component: () => import('@/views/public-view/Redirect.vue'),
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/public-view/404.vue'),
      meta: {
        title: '404',
      },
    },
  ],
}

export const publicRoutes = [
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/public-view/Home.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/public-view/Login.vue'),
  },
]

const createRoutes = () => {
  chatRoute.children.push(...commonRoutes)
  return [layoutRoute, ...publicRoutes]
}

export const Router = createRouter({
  history: createWebHistory(process.env.VUE_APP_BASE_URL),
  routes: createRoutes(),
})

Router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const appStore = useApp()
  let targetPath = ''
  if (appStore.token) {
    const channelStore = useChannel()
    const userStore = useUser()
    if (appStore.getInfoFinish) {
      if (to.path === '/') {
        if (targetPath) {
          next(targetPath)
        } else {
          next({
            path: '/chat',
            query: {
              channelId: channelStore.dialog?.id,
            },
          })
        }
      } else {
        next()
      }
    } else {
      await getInfo({ frontName: 'Fiz-EIM' })
      const resList = await Promise.all([
        getChatChannelList({ includeDirect: true }),
        getChannelMsgCount(userStore.userInfo.userId),
      ])
      if (resList[0].code === 200) {
        channelStore.setChannelList(resList[0].rows)
        const dialog = resList[0].rows.find((i) => i.id === channelStore.dialog?.id)
        if (dialog) {
          channelStore.setDialog(dialog)
        }
      }
      if (resList[1].code === 200) {
        channelStore.setMsgStatisticsMap(resList[1].rows)
      }
      if (to.path === '/') {
        if (targetPath) {
          next(targetPath)
        } else {
          next({
            path: '/chat',
            query: {
              channelId: channelStore.dialog?.id,
            },
          })
        }
      } else {
        next(to.fullPath)
      }
    }
  } else {
    if (to.path.startsWith('/home') || to.path.startsWith('/login')) {
      next()
    } else {
      next({
        path: '/home',
        query: {
          to: '/login',
        },
      })
    }
  }
})

Router.afterEach(() => {
  NProgress.done()
})
